package com.johnson.news.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.johnson.news.R;
import com.johnson.news.activity.WebViewActivity;

/**
 * A simple {@link Fragment} subclass.
 */
public class WebViewFragment extends Fragment {
    String url;
    public WebViewFragment(String url) {
        // Required empty public constructor
        this.url = url;
    }

    View rootView;
    WebView webView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_web_view, container, false);
            initWebView();
        }

        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(webView != null)
            webView.clearCache(true);
    }

    void initWebView() {
        webView = rootView.findViewById(R.id.webview);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(WebViewActivity.intent_key_url, url);
                startActivity(intent);
                return true;
            }
        });

        webView.loadUrl(url);
    }
}
